package ClientCommands;

import java.io.IOException;

import org.json.simple.JSONObject;

import Annotations.IsClientCommand;
import Commands.ClientCommandBase;
import Commands.ExecuteMethod;
import DomainLayer.UserEntity;
import DomainLayer.UserStateValueObject;
import Helpers.ApplicationLogger;
import Presenters.JSONPresenter;
import Presenters.RCodeRealtedPresenter;

@IsClientCommand
public class AuthentificateUser extends ClientCommandBase<JSONPresenter>
{
	private class UserJSONPresenter extends RCodeRealtedPresenter implements JSONPresenter{

		public UserJSONPresenter() 
		{
			setRCode(-1); /*not authentificated*/
		}
		
		public UserJSONPresenter(UserEntity user)
		{
			if(user != null)
			{
				setId(user.getId());
				setLogin(user.getUserInfo().getLogin());
				setFrendlyName(String.format("%1$s %2$s", user.getUserInfo().getFirstName(), user.getUserInfo().getSecondName()));
				setSessionId(user.getUserState().getSessionId());
				setRCode(0);
			}
		}
		
		private Integer id = -1;
		public void setId(Integer id) {
			this.id = id;
		}

		public Integer getId() {
			return id;
		}	
		
		private String login;
		
		public String getLogin() {
			return login;
		}

		public void setLogin(String login) {
			this.login = login;
		}
		
		private String frendlyName;
		

		public String getFrendlyName() {
			return frendlyName;
		}

		public void setFrendlyName(String frendlyName) {
			this.frendlyName = frendlyName;
		}
		
		private String sessionId;

		public String getSessionId() {
			return sessionId;
		}

		public void setSessionId(String sessionId) {
			this.sessionId = sessionId;
		}
		
		public String toJSONString() {

			StringBuffer sb = new StringBuffer();
			sb.append("{");
				sb.append("\"" + JSONObject.escape("RCode") + "\"");
				sb.append(":");
				sb.append("\"" + JSONObject.escape(getRCode().toString()) + "\"");
				sb.append(",");
				sb.append("\"" + JSONObject.escape("SessionID") + "\"");
				sb.append(":");
				sb.append(getSessionId() == null ? JSONObject.escape(null) : "\"" + JSONObject.escape(getSessionId()) + "\"");
				sb.append(",");
				sb.append("\"" + JSONObject.escape("Id") + "\"");
				sb.append(":");
				sb.append("\"" + JSONObject.escape(getId().toString()) + "\"");
				sb.append(",");
				sb.append("\"" + JSONObject.escape("Login") + "\"");
				sb.append(":");
				sb.append("\"" + JSONObject.escape(getLogin()) + "\"");
				sb.append(",");
				sb.append("\"" + JSONObject.escape("FrendlyName") + "\"");
				sb.append(":");
				sb.append("\"" + JSONObject.escape(getFrendlyName()) + "\"");
			sb.append("}");
			return sb.toString();
		}
	}
	
	private String login;
	private String password;
	
	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public AuthentificateUser()
	{
		setCommandName("AuthentificateUser");
		setCommandDescription("Authentificate User By Login and Password");
		setExecuteMethod(ExecuteMethod.ServerOnly);
	}
	
	@Override
	protected void ExecuteInternal() throws IOException {
		JSONPresenter userPresenter = new UserJSONPresenter();
		try {
			
			UserEntity userEntity = (UserEntity) ServiceLayer.ServiceFacade.getInstance().AuthentificationByLoginAndPassword(getLogin(), getPassword());
			
			if (userEntity != null)
	        {
	        	ApplicationLogger.getInstance().LOG.info("Host IP: " + getContext().get("HostIP") + 
	        			" Last IP: " + userEntity.getUserState().getLastIP() + "; Page: " + getSender());
	        	
	        	String hostIp = getContext().get("HostIP");
	        	
	        	if(userEntity.getUserState().getLastIP().equals(hostIp) || "auth".equals(getSender()))
	        	{
		        	userPresenter = new UserJSONPresenter(userEntity);
		        	ApplicationLogger.getInstance().LOG.info("user id: " + userEntity.getId());
		            setIsNull(false);
		            if("auth".equals(getSender())){
			            userEntity.setUserState(new UserStateValueObject(userEntity.getUserState(), null, null, null, hostIp));
			            ServiceLayer.ServiceFacade.getInstance().UpdateUser(userEntity);
		            }
	        	}
	        }
		} catch (Throwable e) {
			ApplicationLogger.getInstance().LOG.error(e.getMessage());
		}

        setResult(userPresenter);
	}
	
	public void FillFromJSON(JSONObject jObj) {
		super.FillFromJSON(jObj);
		setLogin((String)jObj.get("Login"));
		setPassword((String)jObj.get("Password"));
	}
	
	public String toJSONString()
	{
		StringBuffer sb = new StringBuffer();                                  
		sb.append("{");                        
		sb.append("\"" + JSONObject.escape("CommandName") + "\"");                 
		sb.append(":");                 
		sb.append("\"" + JSONObject.escape(getCommandName()) + "\"");                                  
		sb.append(",");                                  
		sb.append("\"" + JSONObject.escape("CommandDescription") + "\"");                 
		sb.append(":");                 
		sb.append("\"" + getCommandDescription() + "\"");   
		sb.append(",");     
		sb.append("\"" + JSONObject.escape("Sender") + "\"");
		sb.append(":");                 
		sb.append("\"" + getSender() + "\"");
		sb.append(","); 
		sb.append("\"" + JSONObject.escape("ExecuteMethod") + "\"");    
		sb.append(":");
		sb.append("\"" + getExecuteMethod() + "\"");   
		sb.append(",");
		sb.append("\"" + JSONObject.escape("Login") + "\"");
		sb.append(":");
		sb.append("\"" + getLogin() + "\"");
		sb.append(",");
		sb.append("\"" + JSONObject.escape("Password") + "\"");
		sb.append(":");
		sb.append("\"" + getPassword() + "\""); 
		sb.append("}");                                  
		return sb.toString();
	}
}
